<?php


namespace App\Models;


use App\User;
use EasyWeChat\Kernel\Messages\Card;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $fillable = ['is_pay','paid_at','is_send','sended_at','is_receive','receive_at','eclpSoNo'];
    //付款状态
    CONST IS_PAY = [
        '0' => '未付款',
        '1' => '已付款',
    ];
    //发货状态
    CONST IS_SEND = [
        '0' => '未发货',
        '1' => '已发货',
    ];
    //收货状态
    CONST IS_RECEIVE = [
        '0' => '未收货',
        '1' => '已收货',
    ];
    CONST IS_CLOSED = [
        '0' => '正常',
        '1' => '已取消',
    ];
    CONST ORDER_STATUS = [
        0,
        1,
        2,
        3
    ];
    CONST ORDER_STATUS_DESC = [
        0 => '待付款',
        1 => '已付款',
        2 => '已发货',
        3 => '已完成',
    ];
    CONST PAY_TYPE = [
        1 => 1,
        2 => 2,
    ];
    CONST PAY_TYPE_DESC = [
        1 => '余额支付',
        2 => '微信支付',
    ];
    public function OrderItems()
    {
        return $this->hasMany(OrderItem::class, 'order_id', 'id');
    }

    public static function findAvailableNo()
    {
        // 订单流水号前缀
        $prefix = date('YmdHis');
        for ($i = 0; $i < 10; $i++) {
            // 随机生成 6 位的数字
            $no = $prefix.str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
            // 判断是否已经存在
            if (!static::query()->where('no', $no)->exists()) {
                return $no;
            }
        }
        \Log::warning('find order no failed');
        return false;
    }

    public function getAddressAttribute($address){
        return json_decode($address,true);
    }

    public static function getOrderStaus($order)
    {
        if ($order['is_pay'] != 1) {
            return 1;
        }
        if ($order['is_pay'] == 1  && $order['is_send'] != 1) {
            return 2;
        }
        if ($order['is_send'] == 1  && $order['is_receive'] != 1) {
            return 3;
        }
        if ($order['is_receive'] == 1) {
            return 4;
        }
    }
    
    public function getNoById($order_id)
    {
        $order = self::find($order_id);
        if ($order) {
            return $order['no'];
        }
        return '';
    }

    public static function sumExpress($city_id,$total_money,$weight)
    {
        $expressarea = ExpressArea::whereAreaId($city_id)->with('express')->first();
        $express_arr = [];
        $user = auth()->user();
        if($expressarea){  //有设置
            $express= $expressarea->express;
            $express_arr['first'] = $express->first;
            $express_arr['continue'] = $express->continue;
            $fee = $user['is_proxy'] ? $express->free_amount : $express->free_retail_amount;
            $express_arr['free'] = $fee;
        }else{   //默认设置
            if ($user['is_proxy']) {
                $express_free = Rule::getRuleInfoByWhere(['key'=>'express_free']); //代理免运费额度
            } else {
                $express_free = Rule::getRuleInfoByWhere(['key'=>'express_retail_fee']); //零售免运费额度
            }
            $express_first = Rule::getRuleInfoByWhere(['key'=>'express_first']); //首重
            $express_continue = Rule::getRuleInfoByWhere(['key'=>'express_continue']); //续重
            $express_arr['first'] = $express_first->value;
            $express_arr['continue'] = $express_continue->value;
            $express_arr['free'] = $express_free->value;
        }
        //首重一公斤
        if($total_money>=$express_arr['free']){
            $express= 0; //免运费
        }else{
            $express = $weight<1 ?  $express_arr['first']: ceil($weight-1)*$express_arr['continue']+$express_arr['first'];//不足首重的话按照首重
        }
        return $express;
    }

    //计算运费
    public static function postfee($address_id, $cart_ids)
    {
        $address = UserAddress::find($address_id);
        if (!$address) {
            uexception('地址不存在');
        }
        $city_id = $address['city_id'];
        $cart_arr = [];
        if (is_string($cart_ids)) {
            $cart_arr = json_decode($cart_ids,true);
        }
        if (!is_array($cart_arr)) {
            uexception('购物列表错误');
        }
        $total_weight = 0;
        $total_price = 0;
        foreach ($cart_arr as $val) {
            $cart = Cart::find($val);
            if ($cart) {
                $total_weight += Product::getProduct($cart['product_id'],'weight')*$cart['amount'];
                $total_price += ProductSku::getPriceById($cart['product_sku_id'])*$cart['amount'];
            }
        }
        $fee = self::sumExpress($city_id, $total_price,$total_weight);
        return $fee;
    }

    //更新京东下单成功返回流水号
    public static function updateJdNo($order_id, $jdNo)
    {
        return Order::where('id', $order_id)->update(['eclpSoNo' =>$jdNo]);
    }

    //获取京东发货状态
    public static function updateSendStatus($order_id, $ship_no)
    {

        $order = order::find($order_id);
        if(!$order){
            uexception('订单号不存在');
        }
        $order->ship_name = '京东物流';
        $order->ship_no = $ship_no;
        $order->sended_at = date('Y-m-d H:i:s');
        $order->is_send = 1;
        $order->order_status = Order::ORDER_STATUS[2];
        $order->order_status_desc = Order::ORDER_STATUS_DESC[2];
        return $order->save();
    }

    //销售总额
    public static function saleMoneyCount()
    {
        $where = [
            ['is_pay', '=', 1],
        ];
        $sum = self::where($where)->sum('total_amount');
        return $sum;
    }

    public static function getCountByStatus($status)
    {
        return self::where('order_status', $status)->count();
    }

}